package cn.gailvlun.gll.presentation.emotion.edit

import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.CheckedTextView
import android.widget.LinearLayout
import cn.gailvlun.gll.R
import cn.gailvlun.gll.config.Constants
import cn.gailvlun.gll.databinding.ActivitySelectEmotionTagBinding
import cn.gailvlun.gll.databinding.ItemSelectEmotionTagHeaderBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.emotion.EmotionEnum
import cn.gailvlun.gll.net.emotion.EmotionTag
import cn.gailvlun.gll.net.emotion.ListEmotionRes
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.IsEmpty
import cn.gailvlun.gll.util.RxUtil
import cn.gailvlun.gll.widget.edittext.BaseFilter
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import rx_activity_result2.Result
import rx_activity_result2.RxActivityResult
import java.util.concurrent.TimeUnit


const val EMOTION_TAG_REQ = "req"

class SelectEmotionTagActivity : BaseActivity() {


    private var mTabs = arrayListOf(
            EmotionEnum.F.desc,
            EmotionEnum.A.desc,
            EmotionEnum.L.desc,
            EmotionEnum.X.desc,

            EmotionEnum.S.desc,
            
            
            EmotionEnum.C.desc,
            EmotionEnum.E.desc
    )

    private var mEmotionStates = arrayListOf(
            EmotionEnum.F,
            EmotionEnum.A,
            EmotionEnum.L,
            EmotionEnum.X,

            EmotionEnum.S,
            
            
            EmotionEnum.C,
            EmotionEnum.E
    )

    private lateinit var mTabAdapter: TabAdapter
    private lateinit var mSelectPanelAdapter: SelectPanelAdapter
    private lateinit var mSearchPanelAdapter: SearchPanelAdapter

    private lateinit var mBinding: ActivitySelectEmotionTagBinding
    private lateinit var mViewModel: SelectEmotionTagViewModel

    companion object {
        fun openActivity(activity: BaseActivity, consumer: Consumer<Result<BaseActivity>>) {
            val intent = Intent(activity, SelectEmotionTagActivity::class.java)
            RxActivityResult.on(activity)
                    .startIntent(intent)
                    .subscribe(consumer)
        }
    }

    override fun initComponent() {
        mBinding = DataBindingUtil.setContentView(mContext, R.layout.activity_select_emotion_tag)
        mViewModel = SelectEmotionTagViewModel(mContext)

        mTabAdapter = TabAdapter(mContext)
        mTabAdapter.setDecorator { holder, position, viewType ->
            val itemBinding = holder?.binding
            if (itemBinding is ItemSelectEmotionTagHeaderBinding) {
                if (position == 0) {
                    itemBinding.tvTab.isChecked = true
                    itemBinding.llTab.isSelected = true
                }

                itemBinding.tvTab.setOnClickListener { view ->
                    for (i in 0 until mBinding.rvSelectPanelTab.childCount) {
                        if (i == position) {
                            itemBinding.tvTab.isChecked = true
                            itemBinding.llTab.isSelected = true
                            continue
                        }
                        mBinding.rvSelectPanelTab.getChildAt(i).findViewById<LinearLayout>(R.id.ll_tab).isSelected = false
                        mBinding.rvSelectPanelTab.getChildAt(i).findViewById<CheckedTextView>(R.id.tv_tab).isChecked = false
                    }
                    getCertainEmotionTags(mEmotionStates[position].name)
                }
            }
        }

        mTabAdapter.setPresenter(mViewModel)
        mBinding.rvSelectPanelTab.adapter = mTabAdapter
        val linearLayoutManager = LinearLayoutManager(mContext)
        mBinding.rvSelectPanelTab.layoutManager = linearLayoutManager

        mSelectPanelAdapter = SelectPanelAdapter(mContext)
        mSelectPanelAdapter.setPresenter(mViewModel)

        val selectPanelLinearLayoutManager = LinearLayoutManager(mContext)
        mBinding.rvSelectPanelContent.adapter = mSelectPanelAdapter
        mBinding.rvSelectPanelContent.layoutManager = selectPanelLinearLayoutManager

        val searchPanelLinearLayoutManager = LinearLayoutManager(mContext)
        mSearchPanelAdapter = SearchPanelAdapter(mContext)
        mSearchPanelAdapter.setPresenter(mViewModel)
        mBinding.rvSearchPanel.layoutManager = searchPanelLinearLayoutManager
        mBinding.rvSearchPanel.adapter = mSearchPanelAdapter

        mBinding.cetSearch.filters = arrayOf(
                object : BaseFilter() {
                    override fun isAllowed(c: Char): Boolean {












                        return true
                    }
                })

    }

    override fun createHandler() {
        val obEditor = RxTextView.editorActionEvents(mBinding.cetSearch).map { mBinding.cetSearch.text }
        val obInput = RxTextView.textChanges(mBinding.cetSearch)

        Observable.merge(obEditor, obInput)
                .debounce(Constants.Search.debounce.toLong(), TimeUnit.MILLISECONDS)
                .skip(1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { charSequence -> getSearchResultData(charSequence.toString()) }

        mBinding.ibBack.setOnClickListener { view ->
            onBackPressed()
        }
    }

    override fun loadData(savedInstanceState: Bundle?) {
        mTabAdapter.addAll(mTabs, TabAdapter.Type.CONTENT.ordinal)
        getCertainEmotionTags(mEmotionStates[0].name)
    }

    private var defaultData: MutableList<EmotionTag> = ArrayList()
    private var recommendData: MutableList<EmotionTag> = ArrayList()
    private fun getCertainEmotionTags(emotionState: String) {
        val pd = DialogUtil.showIndeterminate(mContext)
        HttpMethods.getEmotionService()
                .getCertaionEmotionTags(emotionState)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<List<EmotionTag>>() {
                    override fun onSuccess(response: List<EmotionTag>?) {
                        pd.dismiss()
                        mBinding.invalidateAll()
                        mSelectPanelAdapter.clear()
                        defaultData.clear()
                        recommendData.clear()

                        for (tag in response!!) {
                            if (tag.top == 0) {
                                defaultData.add(tag)
                            } else {
                                recommendData.add(tag)

                            }
                        }
                        if (defaultData.size > 0) {

                            mSelectPanelAdapter.add(defaultData[0], SelectPanelAdapter.Type.HEADER.ordinal)
                            mSelectPanelAdapter.addAll(defaultData, SelectPanelAdapter.Type.CONTENT.ordinal)
                        }

                        if (recommendData.size > 0) {
                            mSelectPanelAdapter.add(recommendData[0], SelectPanelAdapter.Type.HEADER.ordinal)
                            mSelectPanelAdapter.addAll(recommendData, SelectPanelAdapter.Type.CONTENT.ordinal)

                        }


                    }

                    override fun onFailure(errMsg: String?, response: List<EmotionTag>?, code: Int) {
                        pd.dismiss()
                        DialogUtil.showError(mContext, errMsg)
                    }
                })
    }


    fun getSearchResultData(keywords: String?) {
        HttpMethods.getEmotionService()
                .findEmotionTags(keywords)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<ListEmotionRes<EmotionTag>>() {
                    override fun onSuccess(response: ListEmotionRes<EmotionTag>?) {
                        mBinding.invalidateAll()
                        mSearchPanelAdapter.clear()
                        mBinding.llSearchPanel.visibility = View.VISIBLE
                        mBinding.llSelectPanel.visibility = View.GONE

                        if (response != null) {
                            val preciseResult = response.preciseResult
                            val likeResults = response.likeResults

                            if (preciseResult == null) {
                                
                                val userCreated = EmotionTag()

                                val text = mBinding.cetSearch.text.toString().trim()
                                if (!IsEmpty.string(text)) {
                                    userCreated.title = text
                                    userCreated.isUserCreated = true
                                    likeResults.add(0, userCreated)
                                    mSearchPanelAdapter.addAll(likeResults, SearchPanelAdapter.Type.CONTENT.ordinal)
                                }

                            } else {
                                mSearchPanelAdapter.add(preciseResult, SearchPanelAdapter.Type.CONTENT.ordinal)
                            }


                        }

                    }

                    override fun onFailure(errMsg: String?, response: ListEmotionRes<EmotionTag>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }
                })
    }

}